﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Diagnostics;
using System.Reflection;
using System.Web.UI.HtmlControls;
using RestSharp;
using System.Collections.Generic;
using SlamCms.Configuration;
using System.Linq;

namespace SlamCms.SharePoint.WebParts
{
    [ToolboxItemAttribute(false)]
    public class VersionCheck : WebPart
    {
        protected override void CreateChildControls()
        {
            
            string slamCmsID = "";
            if (SPContext.Current.Web.Properties["SlamCmsId"] != null)
            {
                slamCmsID = SPContext.Current.Web.Properties["SlamCmsId"];
            }

            try
            {
                Version version;

                if (HttpRuntime.Cache.Get("SlamCmsVersions") != null)
                {
                    version = HttpRuntime.Cache.Get("SlamCmsVersions") as Version;
                }
                else
                {
                    version = GetVersion();
                    HttpRuntime.Cache.Add("SlamCmsVersions", version, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(10, 0, 0), System.Web.Caching.CacheItemPriority.Normal, null);
                }

                //var versionRequest = GetVersion();

                HtmlGenericControl iFrame = new HtmlGenericControl("iframe");
                iFrame.ID = "versionCheckFrame";
                iFrame.Attributes.Add("width", "100%");
                iFrame.Attributes.Add("height", "230");
                iFrame.Attributes.Add("frameborder", "0");
                iFrame.Attributes.Add("scrolling", "yes");
                iFrame.Attributes.Add("marginwidth", "0");
                iFrame.Attributes.Add("marginheight", "0");

                string source = String.Format("http://slamcms.com/checkversion/{0}?Frontend={1}&SharePoint={2}&Core={3}&Slam={4}", slamCmsID, version.FrontEnd, version.SharePoint, version.Core, version.Slam);
                
                iFrame.Attributes.Add("src", source);
                Controls.Add(iFrame);
            }
            catch (Exception ex)
            {
                HtmlGenericControl error = new HtmlGenericControl("div");
                error.InnerHtml = "The version can not be displayed.";
                Controls.Add(error); ;
            }

        }

        #region Methods


        private Version GetVersion()
        {
            Version returnVersion = new Version();
            var apiVersion = APIVersion();

            returnVersion.Core = apiVersion.SlamCmsCore.AssemblyVersion;
            returnVersion.FrontEnd = apiVersion.SlamCms.AssemblyVersion;
            returnVersion.SharePoint = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductVersion;

            var slamAssembly = AppDomain.CurrentDomain.GetAssemblies().Where(o=>o.Location.EndsWith("Slam.dll")).FirstOrDefault();
            if (slamAssembly != null)
                returnVersion.Slam = FileVersionInfo.GetVersionInfo(slamAssembly.Location).ProductVersion;
            else 
                returnVersion.Slam = String.Empty;
           
            return returnVersion;
        }

        private VersionResult APIVersion()
        {
            var request = new RestRequest("_admin/version");
            var client = new RestClient(ConfigurationManager.Environment.DefaultApplication.FrontEndUrl.TrimEnd('/'));
            var response = client.Execute<VersionResult>(request);
            if (response.StatusCode != System.Net.HttpStatusCode.OK)
                throw new Exception("There was an issue getting versions from "+client.BaseUrl);

           return response.Data;
        }

        #endregion
    }


    public class Version
    {
        public string FrontEnd { get; set; }
        public string Core { get; set; }
        public string SharePoint { get; set; }
        public string Slam { get; set; }
    
    }

    public class VersionResult
    {
        public APIVersion SlamCms { get; set; }
        public APIVersion SlamCmsCore { get; set; }
        
    }

    public class APIVersion
    {
        public string AssemblyVersion { get; set; }
        public string ProductVersion { get; set; }
        public string FileVersion { get; set; }
    
    }
}
